<template>
  <div v-if="pageStatus === 1">
    <ContentWrap>
      <!-- 搜索工作栏 -->
      <el-form ref="queryFormRef" :inline="true" :model="paramsData" class="-mb-10px" label-width="68px">
        <el-form-item label="项目名称" prop="name">
          <el-input v-model="paramsData.name" class="!w-300px" clearable placeholder="请输入项目名称" @keyup.enter="handleQuery" />
        </el-form-item>

        <el-form-item label="项目编号" prop="code">
          <el-input v-model="paramsData.code" class="!w-300px" clearable placeholder="请输入项目编号"
            @keyup.enter="handleQuery" />
        </el-form-item>

        <el-form-item label="合同名称" prop="contractName">
          <el-input v-model="paramsData.contractName" class="!w-300px" clearable placeholder="请输入合同名称" @keyup.enter="handleQuery" />
        </el-form-item>
        
        <el-form-item label="合同编号" prop="contractNumber">
          <el-input v-model="paramsData.contractNumber" class="!w-300px" clearable placeholder="请输入合同编号"
            @keyup.enter="handleQuery" />
        </el-form-item>

        <el-form-item label="负责人" prop="leaderId">
          <SelectScroll class="!w-300px" v-model="paramsData.leaderId" clearable placeholder="请选择负责人" @change="selectChange" />
        </el-form-item>
        <el-form-item>
          <el-button v-hasPermi="['wise:project:query']" @click="handleQuery">
            <Icon class="mr-5px" icon="ep:search" />
            搜索
          </el-button>
          <el-button @click="resetQuery">
            <Icon class="mr-5px" icon="ep:refresh" />
            重置
          </el-button>
          <el-button v-hasPermi="['wise:project:create']" plain type="primary" @click="openForm(1)">
            <Icon class="mr-5px" icon="ep:plus" />
            新增
          </el-button>
          <el-button v-hasPermi="['wise:project:export']" :loading="exportLoading" plain type="success"
            @click="handleExport">
            <Icon class="mr-5px" icon="ep:download" />
            导出
          </el-button>
        </el-form-item>
      </el-form>
    </ContentWrap>
    <!-- 列表 -->
    <ContentWrap>
      <el-table v-loading="loading" :data="tableData" @selection-change="tableSelectionChange">
        <el-table-column type="selection" width="30" />
        <template v-for="item in tableColumn" :key="item.prop">
          <el-table-column
            show-overflow-tooltip
            :width="item.width"
            :align="item.align ? item.align : 'center'" 
            :label="item.label"
            :prop="item.prop"
          >
            <template #default="scope">
              <div v-if="item.prop === 'contractNumber'" @click="goContract(scope.row.mainContractId)">
                <span style="color: #409eff;cursor: pointer;">{{ scope.row.contractNumber }}</span>
              </div>
              <div v-else-if="item.prop == 'createTime'">
                <p>创建时间：{{ scope.row.createTime ? formatDate(scope.row.createTime) : '-' }}</p>
                <p>更新时间：{{ scope.row.updateTime ? formatDate(scope.row.updateTime) : '-' }}</p>
              </div>
              <div v-else-if="item.prop == 'creator'">
                <p>创建：{{ scope.row.creator ? scope.row.creator : '-' }}</p>
                <p>更新：{{ scope.row.updater ? scope.row.updater : '-' }}</p>
              </div>
              <div v-else>
                {{ scope.row[item.prop] ? scope.row[item.prop] : '-' }}
              </div>
            </template>
          </el-table-column>
        </template>

        <el-table-column :width="200" align="center" label="操作">
          <template #default="scope">
            <el-button v-hasPermi="['wise:project:update']" link type="primary" @click="openForm(2, scope.row.id)">
              编辑
            </el-button>
            <el-button v-hasPermi="['wise:project:delete']" link type="danger" @click="handleDelete(scope.row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>

      </el-table>


      <!-- 分页 -->
      <Pagination v-model:limit="paramsData.pageSize" v-model:page="paramsData.pageNo" :total="total" @pagination="getList" />
    </ContentWrap>
  </div>

  <!-- 新增、编辑页 -->
  <projectForm v-else ref="formRef" />
</template>
<script setup>
  import { ref, nextTick, provide, reactive } from "vue"
  import { ArrowDown, CircleClose } from '@element-plus/icons-vue'
  import projectForm from './projectForm.vue'
  import { formatDate } from '@/utils/formatTime'
  import { defaultProps, handleTree } from '@/utils/tree'
  import * as DeptApi from '@/api/system/dept'
  import * as ProjectApi from '@/api/viewsApi/project'
  import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
  import SelectScroll from './selectScroll.vue'
  import download from '@/utils/download'
  const router = useRouter()
  const { wsCache } = useCache('sessionStorage')
  const userList = wsCache.get(CACHE_KEY.USER_LIST) || []
  provide('userList', userList)
  const personalDialogRef = ref(null)
  const pageStatus = ref(1) // 1列表页  2新增编辑页
  const hoverIcon = ref(false) // 负责人图标是否悬停
  const queryFormRef = ref() // 搜索的表单
  const exportLoading = ref(false) // 导出的加载中
  const paramsData = reactive({
    name: '', // 项目名称
    code: '', // 项目编号
    contractName: '', // 合同名称
    contractNumber: '', // 合同编号
    leaderId: '', // 项目负责人
    pageNum: 1,
    pageSize: 10,
    ids: [],
  })
  const loading = ref(true) // 列表的加载中
  const total = ref(0) // 列表的总页数
  const tableData = ref([]) // 列表的数据
  const tableColumn = ref([
    { prop: 'code', label: '项目编号', align: 'center', width: 160},
    { prop: 'name', label: '项目名称', align: 'center', },
    { prop: 'projectType', label: '项目类型', align: 'center'},
    { prop: 'contractName', label: '关联合同', align: 'center'},
    { prop: 'contractNumber', label: '合同编号', align: 'center', width: 180, type: 'number'},
    { prop: 'departmentName', label: '所属部门', align: 'center'},
    { prop: 'leaderName', label: '负责人', align: 'center'},
    { prop: 'createTime', label: '时间', align: 'center', width: 230},
    { prop: 'creator', label: '操作人', align: 'center', width: 220},
  ]) // 表格的列
  const selectIds = ref([])
  const formRef = ref()
  const message = useMessage() // 消息弹窗
  const { t } = useI18n() // 国际化
  const deptTree = ref() // 树形结构
  provide('deptTree', deptTree)

  const getList = async () => {
    loading.value = true
    try {
      const data = await ProjectApi.getProjectList(paramsData)
      data.list.forEach(item => {
        if(item.departmentId){
          item.departmentName = findDeptNameById(deptTree.value, item.departmentId)
        }else{
          item.departmentName = '-'
        }
      })
      tableData.value = data.list
      total.value = data.total
    } finally {
      loading.value = false
    }
  }
  provide('getList', getList)

  /** 负责人选择器改变 */
  const selectChange = (data) => {
    console.log(data, '选中的值');
    
  }

  /** 获得部门树 */
  const getTree = async () => {
    deptTree.value = []
    const data = await DeptApi.getSimpleDeptList()
    deptTree.value = handleTree(data)
  }

  const tableSelectionChange = (selection) => {
    selectIds.value = selection.map(item => item.id)
  }

  /** 搜索按钮操作 */
  const handleQuery = () => {
    paramsData.pageNo = 1
    getList()
  }
  /** 重置按钮操作 */
  const resetQuery = () => {
    paramsData.leaderName = ''
    queryFormRef.value.resetFields()
    handleQuery()
  }
  const openForm = (type, id) => {
    pageStatus.value = 2
    nextTick(() => {
      formRef.value.init(type, id)
    })
  }
  // 跳转合同详情
  const goContract = (id) => {
    router.push({
      path: '/contract',
      query: {
        id,
      }
    })
  }
  const goBack = () => {
    pageStatus.value = 1
    getList()
  }
  provide('goBack', goBack)
  /** 删除按钮操作 */
  const handleDelete = async (id) => {
    try {
      // 删除的二次确认
      await message.delConfirm()
      // 发起删除
      await ProjectApi.deleteProject(id)
      message.success(t('common.delSuccess'))
      // 刷新列表
      await getList()
    } catch {}
  }
  onMounted(async() => {
    await getTree()
    setTimeout(() => {
       getList()
    },10)
  })
  function findDeptNameById(tree, id) {
    for (const node of tree) {
      if (node.id === id) {
        return node.name
      }
      if (node.children && node.children.length > 0) {
        const name = findDeptNameById(node.children, id)
        if (name) return name
      }
    }
    return ''
  }
  provide('findDeptNameById', findDeptNameById)
  const handleExport = async () => {
    if(selectIds.value.length > 0){
      paramsData.ids = selectIds.value
    }
    try {
      // 导出的二次确认
      await message.exportConfirm()
      // 发起导出
      exportLoading.value = true
      const data = await ProjectApi.exportProject(paramsData)
      download.excel(data, '项目管理列表.xls')
    } catch {
    } finally {
      exportLoading.value = false
    }
  }
</script>
<style lang="scss" scoped>
.coord{
  height: 32px;
  box-sizing: border-box;
  padding: 4px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
  color: #636660;
  &:hover{
    border-color: #bcbdc0;
  }
}
.cursor_pointer{
  &:hover{
    border-color: rgb(64, 158, 255);
  }
}
.formInp{
  width: 100%;
}
</style>
